<?php

namespace App\Providers;

use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Events\Manager;
/**
 * \App\Providers\DatabaseServiceProvider
 *
 * @package App\Providers
 */
class DatabaseServiceProvider extends AbstractServiceProvider
{
    /**
     * The Service name.
     * @var string
     */
    protected $serviceName = 'db';

    /**
     * Register application service.
     *
     * @return void
     */
    public function register()
    {
		
		$this->di->set('profiler', function(){
			return new \Phalcon\Db\Profiler();
		}, true);
		
		
        $this->di->setShared(
            $this->serviceName,
            function () {
               
				$eventsManager = new Manager();
				$profiler = $this->get('profiler');
				$eventsManager->attach('db', function($event, $connection) use ($profiler) {
					
					if ($event->getType() == 'beforeQuery') {
						$profiler->startProfile($connection->getSQLStatement());
					}
					
					if ($event->getType() == 'afterQuery') {
						$profiler->stopProfile();
						
					}
				});
				
                $connection = new Mysql($this->getShared('config')->database->toArray());
				$connection->setEventsManager($eventsManager);
                return $connection;
            }
        );



        $this->di->setShared(
            'dbWrite',
            function () {
               
				$eventsManager = new Manager();
				$profiler = $this->get('profiler');
				$eventsManager->attach('dbWrite', function($event, $connection) use ($profiler) {
					
					if ($event->getType() == 'beforeQuery') {
						$profiler->startProfile($connection->getSQLStatement());
					}
					
					if ($event->getType() == 'afterQuery') {
						$profiler->stopProfile();
						
					}
				});
				
                $connection = new Mysql($this->getShared('config')->db2->toArray());
				$connection->setEventsManager($eventsManager);
                return $connection;
            }
        );
		
    }
}
